package com.jkt.rms.validator;
import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;
import com.jkt.rms.commons.utils.StringUtils;
import com.jkt.rms.vo.ResourceRoleVO;
public class ResourceRoleValidator implements Validator {
	@SuppressWarnings("unchecked")
	public boolean supports(Class clazz) {
		return clazz.equals(ResourceRoleVO.class);
	}
	public void validate(Object obj, Errors errors) {
		ResourceRoleVO resourceRoleVO = (ResourceRoleVO) obj;
		//Check mandatory field.
		ValidationUtils.rejectIfEmptyOrWhitespace(errors, "roleName", "error.mandatory.all.field", new String[]{"Role Name"});
		if(errors.getErrorCount()!=0)return;
		ValidationUtils.rejectIfEmptyOrWhitespace(errors, "roleCode", "error.mandatory.all.field", new String[]{"Role Code"});
		if(errors.getErrorCount()!=0)return;
		
		//validation to check field should be alphanumeric only
		if(resourceRoleVO.getRoleName()!= null && !StringUtils.isAlphaNumericWithSpace(resourceRoleVO.getRoleName())){
			errors.rejectValue("roleName","error.alphanumeric.field", new String[]{"Role Name"}, null);
		}
		if(resourceRoleVO.getRoleCode()!= null && !StringUtils.isAlphaNumericWithSpace(resourceRoleVO.getRoleCode())){
			errors.rejectValue("roleCode", "error.alphanumeric.field", new String[]{"Role Code"}, null);
		}
		
		//validation to check maximum length of field
		if(resourceRoleVO.getRoleCode()!= null && !StringUtils.isGreaterThan(resourceRoleVO.getRoleCode(),8)){
			errors.rejectValue("roleCode", "error.maxlength.field", new String[]{"Role Code","8"}, null);
		}
		if(resourceRoleVO.getRoleName()!= null && !StringUtils.isGreaterThan(resourceRoleVO.getRoleName(),100)){
			errors.rejectValue("roleName", "error.maxlength.field", new String[]{"Role Name","100"}, null);
		}
		if(resourceRoleVO.getRoleDesc()!= null && !StringUtils.isGreaterThan(resourceRoleVO.getRoleDesc(),200)){
			errors.rejectValue("roleDesc", "error.maxlength.field", new String[]{"Role Description","200"}, null);
		}
	}
}
